package com.leyu.mall.site.home.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import com.leyu.mall.common.facade.ICmsChannelFacade;
import com.leyu.mall.common.facade.ICmsContentFacade;
import com.leyu.mall.common.facade.ICmsSlideFacade;
import com.leyu.mall.common.facade.IGoodsBrandFacade;
import com.leyu.mall.common.facade.IGoodsCategoryFacade;
import com.leyu.mall.domain.cms.CmsShopConfig;
import com.leyu.mall.domain.cms.CmsSite;
import com.leyu.mall.domain.goods.GoodsBase;
import com.leyu.mall.domain.goods.GoodsCategory;
import com.leyu.mall.domain.member.UserBase;
import com.leyu.mall.service.cms.ICmsNewsService;
import com.leyu.mall.service.cms.ICmsShopConfigService;
import com.leyu.mall.service.cms.ICmsSiteService;
import com.leyu.mall.service.goods.IGoodsBaseService;
import com.leyu.mall.service.news.ISiteNewsService;
import com.leyu.mall.service.sale.ISaleRankListService;
 
/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author OOKK
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@Scope(value = "prototype")
@RequestMapping("/")
public class SiteHomeController {

//	@Autowired
//	private ICmsNewsFacade cmsNewsFacade;
//	
	@Autowired
	private ISiteNewsService siteNewsService;
	@Autowired
	private IGoodsBrandFacade goodsBrandFacade;
	
	@Autowired
	private ICmsChannelFacade cmsChannelFacade;

	@Autowired
	private ICmsContentFacade cmsContentFacade;
	
	@Resource(name = "saleRankListServiceImpl")
	private ISaleRankListService saleRankListFacade;
	
	@Autowired
	private ICmsSlideFacade cmsSlideFacade;
//	@Autowired
//	private IGoodsBaseFacade goodsBaseFacade;
	
	@Autowired
	private IGoodsBaseService goodsBaseFacade;
	
	@Autowired
	private IGoodsCategoryFacade  goodsCategoryFacade;
	
	@Autowired
	private ICmsSiteService  cmsSiteServiceImpl;
	@Autowired
	private ICmsNewsService  cmsNewsServiceImpl;
	

	@Autowired
	private ICmsShopConfigService	cmsShopConfigService;
	
	
//	@RequestMapping("/list")
//	public String list(Model model) {
//		try {
//			List channellist = cmsChannelFacade.getDisplayChannelList();
//			model.addAttribute("channellist", channellist);
//
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		return "inc/list.html";
//	}
	@ExceptionHandler(Exception.class)
	public String exception(Exception e, HttpServletRequest request) {
		request.setAttribute("exception", e);
		return "/error.html";
	}

	@RequestMapping("/bottom")
	public String bottom(Model model) {
		return "/bottom.html";
	}
	@RequestMapping("/header")
	public String header(Model model) {
		return "/header.html";
	}
	@RequestMapping("/menu")
	public String menu(Model model) {
		return "/menu.html";
	}
	 private JsonGenerator jsonGenerator = null;
	    private ObjectMapper objectMapper = null;
	@RequestMapping("/index")
	
	public String index(Model model,HttpServletRequest request) {
		try {
			model.addAttribute("adlist", cmsContentFacade.getDisplayADList());
			model.addAttribute("ranklist", saleRankListFacade
					.getAllSaleRankList());
//			model.addAttribute("list", cmsChannelFacade.getDisplayChannelList());
			model.addAttribute("newslist", siteNewsService.getDisplayNewsList());
			model.addAttribute("slidelist", cmsSlideFacade.getDisplaySlideList());
			model.addAttribute("newgoodslist", goodsBaseFacade.getNewGoodsList());
			model.addAttribute("hotgoodslist", goodsBaseFacade.getHotGoodsList());
			model.addAttribute("groupgoodslist", goodsBaseFacade.getGroupGoodsList());
			model.addAttribute("hotbrandlist",goodsBrandFacade.getAllGoodsBrand());
			model.addAttribute("contractlist",goodsBaseFacade.getContractGoodsList());
			
			List<GoodsBase> contractlist = goodsBaseFacade.getContractGoodsList();
//			goodsBaseFacade.getPromotionGoodsList();
			model.addAttribute("promotiongoodslist", goodsBaseFacade.getPromotionGoodsList());
			
			List<Goodsinfo> newlist = new ArrayList();
			for(GoodsBase gb :contractlist){
				Goodsinfo  gi =  new Goodsinfo();
				gi.setDiscount("discount");
				gi.setId("id");
				gi.setImgLink("imgLink");
				gi.setName("name");
				gi.setNameLink("nameLink");
				gi.setOldPrice("oldPrice");
				gi.setPrice("price");
				gi.setType("type");
				gi.setUrl("url");
				newlist.add(gi);
			}
			model.addAttribute("contractlist",this.listToJson(newlist));
			 
		
//			 List<Goodsinfo> beanList = mapper.readValue(listJson, new TypeReference<List<User>>() {   
//		     });   	
			List<GoodsCategory> allcategorylist = goodsCategoryFacade.getAllGoodsCategory();
			List topList = new ArrayList();
			List onedepthList = new ArrayList();
			List twodepthList = new ArrayList();
			for(GoodsCategory cate : allcategorylist){
				if(cate.getLevel()==1){
					topList.add(cate);
				}else if(cate.getLevel()==2){
					onedepthList.add(cate);
				}else {
					twodepthList.add(cate);
				}
			}
			model.addAttribute("topList", topList);
			model.addAttribute("onedepthList", onedepthList);
			model.addAttribute("twodepthList", twodepthList);
			model.addAttribute("footerlist",this.cmsNewsServiceImpl.getFooterList());
			
//			model.addAttribute("shopconfig",cmsShopConfigService.getCmsShopConfig(1L));
			
			List channellist =  cmsChannelFacade.getDisplayChannelList();
			
			CmsShopConfig shopconfig = cmsShopConfigService.getCmsShopConfig(1L);
			request.getSession().setAttribute("shopconfig", shopconfig);
			request.getSession().setAttribute("channellist", channellist);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//加载站点
		List<CmsSite> siteList;
		try {
			siteList = cmsSiteServiceImpl.getCmsSiteList();
			model.addAttribute("siteList", siteList);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
//		UserBase loginuser = (UserBase)request.getSession().getAttribute("login-user");
		 
		return "/index.html";
	}
	
	  /**
	  * 把map转换成json对象
	  * @param map 
	  * @return 返回一个json
	  */
	 @SuppressWarnings("finally")
	 public static <T> String mapToJson(T obj){
	  String json=null;
	  ObjectMapper mapper=null;
	  try{
	   mapper = new ObjectMapper();
	   json=mapper.writeValueAsString(obj);//把map或者是list转换成
	  }catch(Exception e){
	   e.printStackTrace();
	  }finally{
	   mapper=null;
	   return json;
	  }
	 }
	 
	 @SuppressWarnings("finally")
	 public static <T> String listToJson(T obj){
	  String json=null;
	  ObjectMapper mapper=null;
	  try{
	   mapper = new ObjectMapper();
	   json=mapper.writeValueAsString(obj);//把map或者是list转换成
	  }catch(Exception e){
	   e.printStackTrace();
	  }finally{
	   mapper=null;
	   return json;
	  }
	 }
	 
	 
//	public void writeListJSON() {
//	    try {
//	        List<Goodsinfo> list = new ArrayList<Goodsinfo>();
//	        list.add(bean);
//	        
//	        bean = new AccountBean();
//	        bean.setId(2);
//	        bean.setAddress("address2");
//	        bean.setEmail("email2");
//	        bean.setName("haha2");
//	        list.add(bean);
//	        
//	        System.out.println("jsonGenerator");
//	        //list转换成JSON字符串
//	        jsonGenerator.writeObject(list);
//	        System.out.println();
//	        System.out.println("ObjectMapper");
//	        //用objectMapper直接返回list转换成的JSON字符串
//	        System.out.println("1###" + objectMapper.writeValueAsString(list));
//	        System.out.print("2###");
//	        //objectMapper list转换成JSON字符串
//	        objectMapper.writeValue(System.out, list);
//	    } catch (IOException e) {
//	        e.printStackTrace();
//	    }
//	}
	
//	 User user = new User("abc", "id", 10);   
//     ObjectMapper objectMapper = new ObjectMapper();   
//     
//     System.out.println(json);   
//     User jsonUser = objectMapper.readValue(json, User.class);   
//     System.out.println(jsonUser.getAge());   
//     List<User> list = new ArrayList<User>();   
//     list.add(new User("abc1", "id1", 101));   
//     list.add(new User("abc2", "id2", 102));   
//     list.add(new User("abc3", "id3", 103));   
//     String listJson = objectMapper.writeValueAsString(list);   
//     System.out.println(listJson);   
//     List<User> beanList = objectMapper.readValue(listJson, new TypeReference<List<User>>() {   
//     });   
//     for (User jsonUserList : beanList) {   
//         System.out.println(jsonUserList);   
//     }   
	
	class Goodsinfo {  
		private String id;
		private String url;
		private String imgLink;
		private String oldPrice;
		private String type;
		private String discount;
		private String price;

		private String name;
		private String nameLink;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		public String getImgLink() {
			return imgLink;
		}
		public void setImgLink(String imgLink) {
			this.imgLink = imgLink;
		}
		public String getOldPrice() {
			return oldPrice;
		}
		public void setOldPrice(String oldPrice) {
			this.oldPrice = oldPrice;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		}
		public String getDiscount() {
			return discount;
		}
		public void setDiscount(String discount) {
			this.discount = discount;
		}
		public String getPrice() {
			return price;
		}
		public void setPrice(String price) {
			this.price = price;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getNameLink() {
			return nameLink;
		}
		public void setNameLink(String nameLink) {
			this.nameLink = nameLink;
		}
		
	   
	}

}
